﻿using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ProjectN.Core.Instance.Data;

namespace ProjectN.Core.Instance
{
    internal enum InstanceMode
    {
        Undefined = 0,
        Read = 1,
        Write = 2,
        ReadWrite = 3
    }

    public sealed class Instance : IDisposable
    {
        private readonly DirectoryInfo directory;
        private readonly ImageCollection resource;
        private readonly FileManager<DynamicPage> pages;
        private readonly InstanceMode mode;

        internal Instance(DirectoryInfo instanceDir, InstanceMode mode)
        {
            directory = instanceDir;
            this.mode = mode;
            resource = new (Path.Combine(directory.FullName, "resource"));
            pages = new (Path.Combine(directory.FullName, "handler"));
        }

        internal DirectoryInfo Directory => directory;
        public string Filename { get; set; } = Properties.Resources.S_NO_FN;

        public Guid MajorGuid => pages.PrimaryGuid ?? throw new InvalidOperationException("主要页面 GUID 不存在");
        public DynamicPage MajorPage
        {
            get
            {
                var handler = RequirePage(pages.PrimaryGuid);
                handler.SetAsPrimary();
                return handler;
            }
        }

        private InstanceData? _data;
        public InstanceData Data => _data ??= new(this.resource);

        public Handler<DynamicPage> RequirePage(Guid? guid)
        {

            if (guid.HasValue && pages.Contains(guid.Value))
                return pages.Get(guid.Value);
            var handler = pages.Create(guid);
            handler.Data.Data = Data;
            return handler;
        }

        public void SaveAll() => pages.SaveAll();

        public void Dispose()
        {
            resource.Dispose();
            pages.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}
